﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Web.Framework.Controls;
using Cms.Web.UI.Admin.HelperClasses;
using iLib.Web.UI;
using MasterTemplate = Cms.Domain.MasterTemplate;

namespace Cms.Web.UI.Admin
{
    public partial class EditContentPreview : AdminPage, IEditContentPreviewView
    {
        private EditContentPreviewPresenter _presenter;

        #region IEditContentPreviewView Members

        public int ContentID
        {
            get
            {
                if (ViewState["ContentID"] == null)
                    ViewState["ContentID"] = QueryString.GetInt32ID("id");
                return (int) ViewState["ContentID"];
            }
        }


        public void SetContentID(int id)
        {
            ViewState["ContentID"] = id;
        }


        public int VersionID
        {
            get
            {
                if (ViewState["VersionID"] == null)
                    ViewState["VersionID"] = QueryString.GetInt32ID("versionid");
                return (int) ViewState["VersionID"];
            }
        }


        public string ContextTranslationFile
        {
            get { return "Admin/Translations/EditContentPreview.xml"; }
        }


        public void SetLocales(IList<Locale> locales)
        {
            ddlContentLocales.Items.Clear();
            foreach (Locale l in locales)
                ddlContentLocales.Items.Add(new ListItem(l.GetTranslation(Localization).Name, l.ID.ToString()));
        }


        public int SelectedLocaleID
        {
            get { return int.Parse(ddlContentLocales.SelectedValue); }
            set { ddlContentLocales.SelectedValue = value.ToString(); }
        }


        public void SetVersions(IList<ContentTranslationVersion> versions, int publishedVersionID)
        {
            ContentSetContainerHelper.SetVersions(versions,
                                                  publishedVersionID,
                                                  GetText(this, "NoContentVersions"),
                                                  ref ddlVersions,
                                                  ref lbPublish,
                                                  ref hlPublishLater,
                                                  ref lbSelectPublishedVersion,
                                                  ref llNoVersionPublished);
        }


        public int SelectedVersionID
        {
            get { return int.Parse(ddlVersions.SelectedValue); }
            set { ddlVersions.SelectedValue = value.ToString(); }
        }


        public void SetScheduledPublishings(IList<ScheduledPublishing> scheduledPublishings)
        {
            rpScheduledPublishings.DataSource = scheduledPublishings;
            rpScheduledPublishings.DataBind();
            pnlScheduledPublishings.Visible = scheduledPublishings.Count > 0;
        }


        public void SetHeading(string contentName)
        {
            HeadingText = GetText(this, "Heading") + " &mdash; " + contentName;
        }


        public void SetMasterTemplates(IList<MasterTemplate> masterTemplates)
        {
            ddlMasterTemplates.Items.Clear();
            foreach (MasterTemplate mt in masterTemplates)
            {
                ddlMasterTemplates.Items.Add(new ListItem(mt.Name, mt.ID.ToString()));
            }
        }


        public int SelectedMasterTemplateID
        {
            get { return int.Parse(ddlMasterTemplates.SelectedValue); }
            set { ddlMasterTemplates.SelectedValue = value.ToString(); }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _presenter = new EditContentPreviewPresenter(this);
            int selectedContentLocaleIndex = ddlContentLocales.SelectedIndex;
            _presenter.SetLocales();
            _presenter.SetHeading();
            ddlContentLocales.SelectedIndex = selectedContentLocaleIndex;
            if (!Page.IsPostBack)
            {
                _presenter.Initialize();
                HeadingIcon = litIcon.Text;
                hlBack.NavigateUrl = "Admin/SearchContent.aspx";
            }
            hlPublishLater.Attributes.Add("onclick",
                                          "initInlineDateTimePicker(); cms.Dialogs.Confirm(schedulePublishingCallback, '" +
                                          GetText(this, "PublishLaterHeader") +
                                          "', null, '" +
                                          GetText(this, "PublishLaterOK") +
                                          "', '" +
                                          GetText(this, "PublishLaterCancel") +
                                          "', true, null, 'schedulePublishing');");
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            Page.Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">" +
                                                        DatePickerHelper.GetDatePickerSetup(Localization) +
                                                        Environment.NewLine +
                                                        DatePickerHelper.GetInlineDatePickerSetup(Localization, true) +
                                                        "</script>"));
        }


        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);
            ifrContentPreview.Attributes.Add("src", "Admin/ContentPreview.aspx?LocaleID=" + SelectedLocaleID +
                                                    "&MasterTemplateID=" + SelectedMasterTemplateID +
                                                    "&ContentID=" + ContentID +
                                                    "&VersionID=" + SelectedVersionID);
            upnlContent.Update();
            hlEdit.NavigateUrl = "Admin/EditContent.aspx?LocaleID=" + SelectedLocaleID +
                                 "&ContentID=" + _presenter.GetContentID() +
                                 "&VersionID=" + SelectedVersionID +
                                 "&MasterTemplateID=" + _presenter.GetMasterTemplateID() +
                                 "&SaveReturnUrl=" + Server.UrlEncode("EditContentPreview.aspx?id=" + ContentID) +
                                 "&CancelReturnUrl=" + Server.UrlEncode("EditContentPreview.aspx?id=" + ContentID +
                                                                        "&versionid=" + SelectedVersionID);
            upnlButtons.Update();
        }


        protected void ddlMasterTemplates_IndexChanged(object sender, EventArgs e)
        {
            upnlContent.Update();
        }


        protected void ddlLocales_IndexChanged(object sender, EventArgs e)
        {
            ddlContentLocales.SelectedValue = (sender as DropDownList).SelectedValue;
            _presenter.SaveSelectedLocale();
            _presenter.SetVersions();
            upnlContent.Update();
        }


        protected void ddlVersions_IndexChanged(object sender, EventArgs e)
        {
            upnlContent.Update();
        }


        protected void lbPublish_Click(object sender, EventArgs e)
        {
            _presenter.Publish();
        }


        protected void lbSelectPublishedVersion_Click(object sender, EventArgs e)
        {
            ddlVersions.SelectedValue = (sender as LinkButton).CommandArgument;
            upnlContent.Update();
        }


        protected void btnSchedulePublishing_Click(object sender, EventArgs e)
        {
            _presenter.SchedulePublishing(int.Parse(ddlVersions.SelectedValue),
                                           DateTime.Parse(hidScheduledPublishing.Value));
            upnlContent.Update();
        }


        protected void rpScheduledPublishings_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var scheduledPublishing = (ScheduledPublishing) e.Item.DataItem;
            var litVersion = (Literal) e.Item.FindControl("litVersion");
            var litTimestamp = (Literal) e.Item.FindControl("litTimestamp");
            var lbDeleteScheduledPublishing = (LinkButton) e.Item.FindControl("lbDeleteScheduledPublishing");
            litVersion.Text = "#" + scheduledPublishing.ContentTranslationVersion.ID;
            var timestamp = new DateTime(long.Parse(scheduledPublishing.Timestamp));
            litTimestamp.Text = timestamp.ToShortDateString() + " " + timestamp.ToShortTimeString();
            lbDeleteScheduledPublishing.CommandArgument = scheduledPublishing.ID.ToString();
        }


        protected void lbDeleteScheduledPublishing_Click(object sender, EventArgs e)
        {
            _presenter.DeleteScheduledPublishing(int.Parse((sender as LinkButton).CommandArgument));
            upnlContent.Update();
        }
    }
}